package com.dh.blog.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.crypto.hash.SimpleHash;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.ewei.web.common.exception.MessageRuntimeException;

/**
 * 加密工具
 * @author David
 *
 */
public class Encrypter {
	private static final String UTF8 ="UTF-8";
	private static final Logger logger = LogManager.getLogger(Encrypter.class);
	/**
	 * 默认的密码加密方法
	 * @param loginname
	 * @param password
	 */
	public static String encryptPwd(String loginname,String password){
		return null;
	}
	/**
	 * 调用外部工具加密
	 * @param loginname
	 * @param password
	 * @param tool
	 */
	public static String encryptPwd(String loginname,String password,
			String tool){
		String encrypt = null;
		if("shiro".equals(tool)){
			encrypt =  new SimpleHash("md5",password, loginname).toHex();
		}else{
			throw new MessageRuntimeException("encrypt tool isn't existed!");
		}
		return encrypt;
	}
	/**
	 * BASE64加密
	 * @param encode
	 * @return
	 * @throws Exception
	 */
	public static String base64Encoder(String encode){
		try {
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(encode.getBytes(UTF8));
		} catch (UnsupportedEncodingException e) {
			logger.info(e);
			throw new MessageRuntimeException();
		}
	}
	/**
	 * BASE64解密
	 * @param dest
	 * @return
	 * @throws Exception
	 */
	public static String base64Decoder(String dest){
		try {
			BASE64Decoder decoder = new BASE64Decoder();
			return new String(decoder.decodeBuffer(dest),UTF8);
		} catch (UnsupportedEncodingException e) {
			logger.info(e);
			throw new MessageRuntimeException(e);
		} catch (IOException e) {
			logger.info(e);
			throw new MessageRuntimeException(e);
		}
	}
	/**
	 * MD5签名
	 * @param src
	 * @return
	 * @throws Exception
	 */
	public static String md5Digest(String src) throws Exception{
		MessageDigest md = MessageDigest.getInstance("MD5");
		byte[] b = md.digest(src.getBytes(UTF8));
		return  byte2HexStr(b);
	}
	private static String byte2HexStr(byte[] b){
		StringBuilder sb = new StringBuilder();
		for(int i = 0;i<b.length;i++){
			String s = Integer.toHexString(b[i] & 0xFF);
			if(s.length() == 1){
				sb.append("0");
			}
			sb.append(s.toUpperCase());
		}
		return sb.toString();
	}
}
